﻿using Devonline.AspNetCore;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Devonline.Identity.Admin.Controllers;

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class AttachmentsController : ControllerBase
{
    private readonly IAttachmentService<IdentityDbContext> _attachmentService;
    public AttachmentsController(IAttachmentService<IdentityDbContext> attachmentService)
    {
        _attachmentService = attachmentService;
    }

    /// <summary>
    /// 使用限定的 businessType 和 businessKey 获取附件
    /// </summary>
    /// <param name="businessType"></param>
    /// <param name="businessKey"></param>
    /// <returns></returns>
    [HttpGet]
    public async Task<IActionResult> GetAsync(string businessType, string businessKey)
    {
        var attachments = await _attachmentService.GetAttachmentsAsync(businessType, businessKey);
        return attachments == null ? NotFound() : Ok(attachments);
    }

    /// <summary>
    /// 文件下载, 提供完整文件相对路径的单个文件下载
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    [HttpGet("Download")]
    public async Task<IActionResult> Download(string fileName) => await _attachmentService.GetAttachmentFileAsync(fileName);

    /// <summary>
    /// 文件下载, 提供类似于文件夹目录结构的访问方式进行下载
    /// 文件路径只支持一级路径, 适用于访问自动保存的文件或者符合目录规范的文件
    /// </summary>
    /// <param name="filePath">文件路径(只支持一级路径)</param>
    /// <param name="fileName">文件名</param>
    /// <returns></returns>
    [HttpGet("Files/{filePath}/{fileName}")]
    public async Task<IActionResult> Files(string filePath, string fileName) => await _attachmentService.GetAttachmentFileAsync(fileName, filePath);

    /// <summary>
    /// 文件上传, 支持批量上传, 返回 UploadResult 集合
    /// </summary>
    /// <param name="files"></param>
    /// <returns></returns>
    [HttpPost("Upload")]
    public async Task<IActionResult> Upload(IEnumerable<IFormFile> files) => Ok(await _attachmentService.UploadAsync(files));

    /// <summary>
    /// 文件删除, 支持由逗号间隔的文件名批量删除
    /// </summary>
    /// <param name="fileNames"></param>
    /// <returns></returns>
    [HttpDelete("Delete")]
    public IActionResult Delete(string fileNames)
    {
        var files = fileNames.Split(AppSettings.CHAR_COMMA, StringSplitOptions.RemoveEmptyEntries);
        if (files.Any())
        {
            _attachmentService.Delete(files);
        }

        return Ok();
    }
}